package com.shop.Service.impl;

import com.shop.Service.LogService;
import com.shop.mapper.LogMapper;
import com.shop.pojo.Log;
import com.shop.pojo.Message;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;

@Service
public class LogServiceImpl implements LogService {
    @Override
    public Message<List<Log>> selectLog(int limit) throws Exception {
        Message<List<Log>> message = new Message<>();
        InputStream stream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        LogMapper mapper = sqlSession.getMapper(LogMapper.class);
        List<Log> logList = mapper.selectLog(limit);
        message.setMessage("获取成功");
        message.setData(logList);
        return message;
    }

    @Override
    public Message<String> addLog(String username, boolean status, String message) throws Exception {
        Message<String> message2 = new Message<>();
        InputStream stream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        LogMapper mapper = sqlSession.getMapper(LogMapper.class);
        Log log =new Log();
        log.setUsername(username);
        log.setStatus(status);
        log.setMessage(message);
        mapper.addLog(log);
        sqlSession.commit();
        message2.setMessage("添加成功");
        message2.setData("添加成功");
        return message2;
    }
}
